/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package actions

import (
	"gitee.com/tugoer/orivil/mux"
	"strconv"
	"net/url"
)

var Index = []*mux.Action{
	{
		Name: "Get Article Html",
		Method: "GET",
		Route: "article",
		Handler: func(ctx *mux.Context) {
			ctx.View("article")
		},
	},
	{
		Name: "Redirect Html",
		Method: "GET",
		Route: "redirect",
		Handler: func(ctx *mux.Context) {
			idStr := ctx.Query().Get("id")
			id, _ := strconv.Atoi(idStr)
			channel := ctx.Query().Get("channel")
			u := redirectData.GetUrl(id)
			if u == "" {
				u = ctx.Query().Get("url")
			}
			counts := ctx.Query()["counts"]
			var countScript string
			for _, src := range counts {
				src, _ = url.QueryUnescape(src)
				countScript += `<script async="async" src="` + src + `" language="JavaScript" type="text/javascript"></script>`
			}
			ctx.WriteString(newRedirectHtml(u, idStr, channel, countScript))
		},
	},
}

func newRedirectHtml(URL, id, channel, countScript string) string {
	return `<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>`+id+`</title>`+
		countScript +
`</head>
<body>
<div style="position: fixed;z-index: 99999999;right: 0;top: 0;left: 0;bottom: 0;background-color: white"></div>
</body>
<script>
	window.onload = function(){
		window.location.href = "`+URL+`";
	}
</script>
</html>`
}